const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlFormatter = require('url');
// 假设dataBase为数据库
let dataBase={};
http.createServer(function (req, res) {
    let str = '';
    req.on('data', function (data) {
        str += data;
    });
    req.on('end', function () {
        const obj = urlFormatter.parse(req.url, true);
        const pathname = obj.pathname; //  /ajax.html
        const getData = obj.query; //{'type':'reg',name':'test','pass':1}
        const postData = querystring.parse(str);
        const path = `./www${req.url}`;
        // 这里假设访问 /user为接口，其他为文件
        if (pathname == '/user') {
            switch (postData.type) {
                case 'reg':
                    // 1.检查用户名是否存在
                    // 2.若不存在在数据库中写入用户名、密码
                    if(dataBase[postData.name]){
                        res.write('{"code":0,"msg":"用户名已经存在"}')
                    }else{
                        dataBase[postData.name]=postData.pass
                        res.write('{"code":1,"msg":"注册成功"}')
                    }
                    break;
                case 'login':
                    //1.检查用户是否已经注册 
                    // 2.检查密码是否正确
                    if(dataBase[postData.name]==undefined){
                        res.write('{"code":0,"msg":"该用户未注册"}')
                    }else if(dataBase[postData.name]==postData.pass){
                        res.write('{"code":1,"msg":"登录成功"}')
                    }else{
                        res.write('{"code":0,"msg":"密码错误"}')
                    }
                    break;
                default:
                    res.write('{"code":0,"msg":"未知的类型"}')
                    break;
            }
            res.end();
        } else {
            fs.readFile(path, function (err, data) {
            console.log(err)

                if (err) {
                    res.write('404');
                } else {
                    res.write(data);
                }
                res.end();
            });
        }
    });

}).listen(8080)